package com.zch.socket.aio.server2;

import com.zch.socket.common.model.ResponseModel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ServerWriterHandler implements CompletionHandler<Integer,ByteBuffer> {
    private AsynchronousSocketChannel channel;

    public ServerWriterHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }
    @Override
    public void completed(Integer result, ByteBuffer attachment) {

      /*  //完成全部数据的写入
        if (attachment.hasRemaining()) {
            channel.write(attachment, attachment, this);
        }*/
        System.out.println("服务端 返回 消息成功");
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        channel.read(buffer,buffer,new ServerReadHandler(channel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
       System.out.println("服务端写入异常");
       exc.printStackTrace();
        //出现异常显示的关闭通道，aio的通道是不会主动关闭的，可以理解为可复用的长连接。
        try {
            channel.close();
        } catch (IOException e) {
        }
    }
}
